﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using AccessControl.Business;
using AccessControl.Common.Enumerations;
using AccessControl.Utility.EnumHelper;
using AccessControl.Utility.Grid;


namespace AccessControl.ManagementReport.Form
{
    public partial class Report : System.Windows.Forms.Form
    {

        #region Field

        private byte[] DefaultLayout;
        private CheckMarkSelection CheckedView;

        #endregion

        #region Constructor

        public Report()
        {
            InitializeComponent();


            CheckedView = new CheckMarkSelection(MainView);
            CheckedView.CheckMarkColumn.VisibleIndex = 100;


            dtpDate.EndDate = DateTime.Now.Date.AddDays(1);
            dtpDate.StartDate = DateTime.Now.Date;


            multiTxtResult.BindData<EventResultConstants>("Key", null, "Value", null, null);
            multitxtWorkflow.BindData(WorkflowBusiness.SelectFull, "pkWorkflow", null, "WorkflowName", "EventName", null);


            multitxtGroup.BindData(GroupBusiness.SelectFullVisible(), "FullPK", null, "GroupName",
                                      "GroupTypeName", null);

            lookUpEditSelectiveColumn.Properties.DataSource = GroupTypeBusiness.SelectAll();
            RefreshGrid();

        }

        #endregion

        #region Private Methods

        private void RefreshGrid()
        {
            var filters = new List<string>();
            if (multitxtWorkflow.FiltersCount > 0) filters.Add(multitxtWorkflow.getFilterString());

            if (multiTxtResult.FiltersCount > 0) filters.Add(multiTxtResult.getFilterString());


            var filterString = (filters.Count > 0
                                    ? " AND " + string.Join(" AND ", filters.ToArray())
                                    : string.Empty);
            

            if (multitxtGroup.FiltersCount > 0)

                filterString += String.Format(
                        " AND EXISTS( SELECT TOP(1) * FROM tblPersonGroup AS PG WHERE (CAST (fkGroupType as varchar))+'-'+(CAST (fkGroup as varchar)) IN {0} AND  PG.fkPerson = tblPerson.pkPerson )", multitxtGroup.getFilterStringArray());
            if ((lookUpEditSelectiveColumn.EditValue == null) || (lookUpEditSelectiveColumn.EditValue == DBNull.Value))
                lookUpEditSelectiveColumn.EditValue = 1;

            var tbl = EventLogBusiness.SelectByFilterForReport(filterString, (int)lookUpEditSelectiveColumn.EditValue, dtpDate.StartDate, dtpDate.EndDate, checkEditLast.Checked);
            grdList.DataSource = tbl;
        }

        #endregion

        #region Event Handler

        private void multitxtWorkflow_ApplyFilter(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void multiTxtResult_ApplyFilter(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void dtpDate_ApplyFilter(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void MainView_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if ((e.Column == gridColumnResult) && (e.Value != null))
                e.DisplayText = ((EventResultConstants)(Byte.Parse(e.Value.ToString()))).GetDescription();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            grdList.ShowPrintPreview();
        }

        private void multitxtGroup_ApplyFilter(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void checkEditLast_CheckedChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void simpleButtonRefresh_Click(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void lookUpEditSelectColumn_EditValueChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void lookUpEditSelectColumn_TextChanged(object sender, EventArgs e)
        {
            gridColumnGroupName.Caption = lookUpEditSelectiveColumn.Text;

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if(MainView!=null){
                var defaultLayout = new MemoryStream();
                MainView.SaveLayoutToStream(defaultLayout);
                DefaultLayout = defaultLayout.ToArray();
                defaultLayout.Close();

                if (Properties.Settings.Default.GridLayout!=null && Properties.Settings.Default.GridLayout != string.Empty)
                {
                    var layout = (byte[])Properties.Settings.Default.GridLayout;
                    var ms = new MemoryStream(layout);
                    MainView.RestoreLayoutFromStream(ms);
                    ms.Close();
                }
            }

            gridColumnGroupName.Caption = lookUpEditSelectiveColumn.Text;

        }

        protected void MainView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.R && e.Control && e.Shift)
            {
                var defaultLayout = new MemoryStream(DefaultLayout);
                MainView.RestoreLayoutFromStream(defaultLayout);
                defaultLayout.Close();
                MainView.BestFitColumns();
            }
            else if (e.KeyCode == Keys.F && e.Control && e.Shift)
                MainView.BestFitColumns();

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Properties.Settings.Default.GridLayout != string.Empty)
            {
                var ms = new MemoryStream();
                MainView.SaveLayoutToStream(ms);
                var layout = ms.ToArray();
                ms.Close();
                Properties.Settings.Default.GridLayout = layout;

            }
        }

        private void MainView_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column == gridColumnIndex)
                if (MainView.IsDataRow(e.RowHandle))
                    e.Value = e.RowHandle + 1;
        }

        #endregion       

    }
}
